<?php

namespace App\Http\Controllers;

use App\Http\Model\AddressModel;
use App\Http\Model\CartModel;
use App\Http\Model\OrderExpressModel;
use App\Http\Model\OrderOrderModel;
use App\Http\Model\OrderOrderItemModel;
use App\Http\Model\OrderProductModel;
use App\Http\Model\OrderSkuModel;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function create(Request $req){
        //userId,$addressId,$cartId
        $data = $this->getReqArray($req->getContent());

        $userId = $data["userId"];

        $addressId = $data["addressId"];

        $cartId = $data["cartId"];

        $add = $this->checkAddressId($userId,$addressId);
        if($add=="error"){
            return response()->json($this->getMsg(ERROR_CODE,"用户地址异常"));
        }

        $sku = $this->getSkuByUserCart($userId,$cartId);


        if($sku=="error"){
            return response()->json($this->getMsg(ERROR_CODE,"商品订单异常"));
        }

        $tmpRes = $this->checkProduct($sku);

        $express = $this->getExpress($tmpRes);

        $om = new OrderOrderModel();

        $orderRes =  $om->create($add,$tmpRes,$express);

        $resRes = [];

        $resRes["code"] = $orderRes="success"?SUCCESS_CODE:ERROR_CODE;

        $resRes["msg"] = $orderRes="success"?ORDER_SUCCESS:ORDER_ERROR;

        return response()->json($resRes);
    }

    private function checkAddressId($userId,$addressId){

        $res = AddressModel::where("user_id",$userId)
            ->where("id",$addressId)->first();

        if(empty($res)){
            return "error";
        }
        return $res;
    }

    private function getSkuByUserCart($userId,$cartId){

        $res = CartModel::where("user_id",$userId)
            ->whereIn("id",$cartId)
            ->where("status",NOR_STATES)
            ->with("sku")
            ->get();

        if(empty($res)){
            return "error";
        }

        return $res;
    }

    private function checkProduct($sku){
        foreach($sku as $s) {
            $s["product"] = OrderSkuModel::where("id", $s["sku_id"])
                ->with("product")
                ->first()["product"];

            if (empty($s["product"])) {
                return "商品不存在";
            }

            if($s["quantity"]>$s["product"]["quantity"]){
                return "库存不足";
            }

        }
        return $sku;
    }

    private function getExpress($cart){
        $expressArr = array();
        $proTotal = 0;

        foreach($cart as $k=>$v){
            $key = $v["product"]["id"];
            $total = round($v["quantity"]*$v["sku"]["price"],2);
            $proTotal += $total;
            $weith = $v["quantity"]*$v["sku"]["weight"];
            if(!array_key_exists($key,$expressArr)){
                $expressArr[$key] = [$total,$weith];
            }else{
                $expressArr[$key][0] += $total;
                $expressArr[$key][1] += $weith;
            }
        }

        $express = 0;
        foreach($expressArr as $product_id => $arr){
            $exp = OrderExpressModel::where("id",$product_id)->select("min_money","weight","fee")->first();
            if($arr[0]<(float)$exp["min_money"]){
                $express += round(($arr[1]/(integer)$exp["weight"]+1)*(float)$exp["fee"]);
            }
        }

        return [$proTotal,$express];
    }
}
